﻿using MyOCR_WPF.Tool;
using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace MyOCR_WPF.OCRHelper
{
    class SouGouOCR : IOCR
    {
        // 搜狗云中开通对应服务应用的 API Key 建议开通应用的时候多选服务
        private static String SecretId;
        // 搜狗云中开通对应服务应用的 Secret Key
        private static String SecretKey;

        public SouGouOCR()
        {
            SecretId = ConfigurationManager.AppSettings["SouGou_Id"];
            SecretKey = ConfigurationManager.AppSettings["SouGou_Key"];
        }

        public string SendImg(Bitmap img)
        {
            string authHost = "http://deepi.sogou.com/api/sogouService";
            RestClient restClient = new RestClient(authHost);
            RestRequest request = new RestRequest(Method.POST);
           
            string baseImg = ImageProcessing.ImageToBase64(img);
            request.AddParameter("service", "basicOpenOcr");
            request.AddParameter("pid", SecretId);
            request.AddParameter("salt", "10012");
            request.AddParameter("lang", "zh-CHS");
            request.AddParameter("image", baseImg);
            request.AddParameter("sign", getSign(baseImg));

            var result = restClient.Execute(request);
            var lst = new List<string>();
            var content = result.Content;
            dynamic json = JsonConvert.DeserializeObject(content);
            foreach (var item in json.result)
            {
                lst.Add(item.content.ToString());
            }
            return string.Join("", lst);
        }

        protected string getSign(string img)
        {
            string sign = string.Format("{0}{1}{2}{3}{4}", SecretId, "basicOpenOcr", "10012", img.Substring(0, 1024), SecretKey);
            var md5 = new MD5CryptoServiceProvider();
            var result = Encoding.UTF8.GetBytes(sign);
            var output = md5.ComputeHash(result);

            return BitConverter.ToString(output).Replace("-", "").ToLower();
        }
    }
}
